<?php


namespace app\service\model;


use app\service\Y;

class ConfigModel extends BaseModel
{

    protected $table = 'config';

    /**
     * 获取配置值
     * @param $key
     * @return array|mixed|object|\think\App|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigValue($key)
    {
        if (!$config = cache('config:' . $key)) {
            $config = self::field('value, remark')->where('key', '=', $key)->find();
            cache('config:' . $key, $config, null, 'config');
        }
        return $config;
    }

    /**
     * 保存数据
     * @param $param
     * @param $id
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveData($param, $id) {
        if ($id > 0) {
            if (self::where('title', '=', $param['title'])->where('id', '<>', $id)->find()) {
                return Y::error('配置名称已存在');
            }

            if (self::where('key', '=', $param['key'])->where('id', '<>', $id)->find()) {
                return Y::error('配置key已存在');
            }

            $data = self::find($id);
            if (!$data) {
                return Y::error('参数错误');
            }

            $data->save($param);
        } else {
            if (self::where('title', '=', $param['title'])->find()) {
                return Y::error('配置名称已存在');
            }

            if (self::where('key', '=', $param['key'])->find()) {
                return Y::error('配置key已存在');
            }
            self::create($param);
        }
        return Y::success([], '保存成功');
    }
}